﻿@using Fluxor.Blazor.Web.Components;
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.ClientStore;
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits FluxorComponent
@inject Radzen.DialogService dialogService
@inject NotificationService notificationService
@inject IState<UpdateClientState> updateClientState
@inject IDispatcher dispatcher

@if (!string.IsNullOrWhiteSpace(ErrorMessage))
{
    <RadzenAlert AllowClose="false" AlertStyle="AlertStyle.Danger" ShowIcon="true" Variant="Variant.Flat" Shade="Shade.Lighter">@ErrorMessage</RadzenAlert>
}

<RadzenTemplateForm Submit=@SubmitAddClientRole TItem="AddClientRole" Data=@addClientRole>
    <!-- Name -->
    <div>
        <RadzenText TextStyle="TextStyle.Subtitle2" TagName="TagName.H3">@Global.Name</RadzenText>
        <RadzenTextBox Name="Name" @bind-Value="@addClientRole.Name" Class="w-100"></RadzenTextBox>
        <RadzenRequiredValidator Component="Name" Text="@Global.NameIsRequired"></RadzenRequiredValidator>
    </div>
    <!-- Description -->
    <div>
        <RadzenText TextStyle="TextStyle.Subtitle2" TagName="TagName.H3">@Global.Description</RadzenText>
        <RadzenTextArea Name="Description" @bind-Value="@addClientRole.Description" Class="w-100"></RadzenTextArea>
    </div>
    <RadzenButton class="mt-1" Variant="Variant.Flat" ButtonType="ButtonType.Submit" ButtonStyle="ButtonStyle.Success" Text="@(updateClientState.Value.IsUpdating ? Global.Adding : Global.Add)" Disabled=@updateClientState.Value.IsUpdating />
</RadzenTemplateForm>

@code {
    [Parameter]
    public string ClientId { get; set; }
    [Parameter]
    public string Id { get; set; }

    AddClientRole addClientRole = new AddClientRole();

    string ErrorMessage { get; set; }

    record AddClientRole
    {
        public string Name { get; set; } = null!;
        public string Description { get; set; } = null!;
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        ErrorMessage = null;
        SubscribeToAction<AddClientRoleFailureAction>((e) =>
        {
            ErrorMessage = e.ErrorMessage;
        });
        SubscribeToAction<AddClientRoleSuccessAction>((e) =>
        {
            dialogService.Close();
        });
    }

    void SubmitAddClientRole(AddClientRole addClientRole)
    {
        dispatcher.Dispatch(new AddClientRoleAction { Id = Id, Name = addClientRole.Name, Description = addClientRole.Description, ClientId = ClientId });
    }
}